package scraper

import (
    "fmt"
    "spam3uk/internal/models"
    "spam3uk/internal/storage"
    "strings"
    "time"

    "github.com/sirupsen/logrus"
)

// PageType 页面类型枚举
type PageType int

const (
	PageTypeModern      PageType = iota // 现代布局：有trim对比和"See Full Specs"按钮 (如Puma)
	PageTypeClassic                     // 经典布局：功能介绍为主，缺少trim对比 (如Focus)
	PageTypePerformance                 // 性能车型：可能有独特布局
	PageTypeUnknown                     // 未知类型
)

// PageTypeInfo 页面类型信息
type PageTypeInfo struct {
	Type              PageType
	HasTrimCompare    bool     // 是否有trim对比功能
	HasSpecsButton    bool     // 是否有"See Full Specs"按钮
	SupportedFeatures []string // 支持的功能列表
}

// TrimScraper trim信息抓取器
type TrimScraper struct {
	storage storage.VehicleStorage
	logger  *logrus.Logger
}

// NewTrimScraper 创建trim抓取器
func NewTrimScraper(storage storage.VehicleStorage, logger *logrus.Logger) *TrimScraper {
	return &TrimScraper{
		storage: storage,
		logger:  logger,
	}
}

// ScrapeTrims 抓取指定model的trim信息
func (ts *TrimScraper) ScrapeTrims(modelName string) error {
	ts.logger.WithField("model", modelName).Info("Starting trim scraping")

    // 通过接口获取车型的detail_url
    detailURL, err := ts.storage.GetVehicleDetailURL(modelName)
	if err != nil {
		return fmt.Errorf("failed to get detail URL for model '%s': %w", modelName, err)
	}

	ts.logger.WithFields(logrus.Fields{
		"model":      modelName,
		"detail_url": detailURL,
	}).Info("Found detail URL, starting page type detection")

	// 🔥 Issue #005: 检测页面类型
	pageTypeInfo := ts.detectPageType(modelName, detailURL)
	ts.logger.WithFields(logrus.Fields{
		"model":            modelName,
		"page_type":        pageTypeInfo.Type,
		"has_trim_compare": pageTypeInfo.HasTrimCompare,
		"has_specs_button": pageTypeInfo.HasSpecsButton,
		"features":         pageTypeInfo.SupportedFeatures,
	}).Info("Page type detected")

    // 清理旧数据（可选）
    if err := ts.storage.DeleteTrimByModel(modelName); err != nil {
		ts.logger.WithError(err).Warn("Failed to clean old trim data")
	}

	// 🔥 Issue #005: 根据页面类型选择不同的抓取策略
    switch pageTypeInfo.Type {
    case PageTypeModern:
        return ts.scrapeModernLayout(modelName, pageTypeInfo)
    case PageTypeClassic:
        return ts.scrapeClassicLayout(modelName, pageTypeInfo)
    case PageTypePerformance:
        return ts.scrapePerformanceLayout(modelName, pageTypeInfo)
    default:
        return ts.scrapeUnknownLayout(modelName, pageTypeInfo)
    }
}

// detectPageType 检测页面类型（基于模型名称和URL分析）
func (ts *TrimScraper) detectPageType(modelName, detailURL string) PageTypeInfo {
	modelLower := strings.ToLower(modelName)

	// 🔥 Issue #005: 基于已知信息进行页面类型判断

	// 现代布局车型：有完整trim对比功能
	if strings.Contains(modelLower, "puma") {
		return PageTypeInfo{
			Type:              PageTypeModern,
			HasTrimCompare:    true,
			HasSpecsButton:    true,
			SupportedFeatures: []string{"trim_compare", "full_specs", "detailed_configs"},
		}
	}

	// 性能车型：可能有特殊布局
	if strings.Contains(modelLower, "st") || strings.Contains(modelLower, "mustang") {
		return PageTypeInfo{
			Type:              PageTypePerformance,
			HasTrimCompare:    false,
			HasSpecsButton:    false,
			SupportedFeatures: []string{"performance_specs", "engine_details"},
		}
	}

	// 经典布局车型：功能介绍为主
	if strings.Contains(modelLower, "focus") || strings.Contains(modelLower, "fiesta") ||
		strings.Contains(modelLower, "mondeo") || strings.Contains(modelLower, "kuga") {
		return PageTypeInfo{
			Type:              PageTypeClassic,
			HasTrimCompare:    false,
			HasSpecsButton:    false,
			SupportedFeatures: []string{"basic_info", "feature_highlights"},
		}
	}

	// 未知类型
	return PageTypeInfo{
		Type:              PageTypeUnknown,
		HasTrimCompare:    false,
		HasSpecsButton:    false,
		SupportedFeatures: []string{"basic_fallback"},
	}
}

// scrapeModernLayout 抓取现代布局页面 (如Puma)
func (ts *TrimScraper) scrapeModernLayout(modelName string, pageInfo PageTypeInfo) error {
	ts.logger.WithField("model", modelName).Info("Using modern layout scraping strategy")

	// 抓取trim基本信息
	trims := ts.getMockTrimDataModern(modelName)

	// 🔥 升级: 使用新的JSON存储方式保存trim和规格信息
	for _, trim := range trims {
		if trim.SeeFullSpecsAvailable {
			// 获取规格数据
			specs := ts.GetMockSpecsDataModern(trim.TrimName, modelName)

			// 🔥 使用新方法：同时保存trim信息和JSON格式的规格
            if err := ts.storage.UpsertTrimWithJSONSpecs(&trim, specs); err != nil {
				ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim with JSON specs")

				// 🔥 如果新方法失败，回退到旧方法以保证兼容性
				ts.logger.WithField("trim", trim.TrimName).Warn("Falling back to legacy storage method")

				// 保存基本信息
                if err := ts.storage.UpsertTrimInfo(&trim); err != nil {
					ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim info")
				}

				// 保存规格信息
                if err := ts.storage.BatchUpsertTrimSpecs(specs); err != nil {
					ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim specs")
				}
			} else {
				ts.logger.WithFields(logrus.Fields{
					"trim":        trim.TrimName,
					"specs_count": len(specs),
				}).Info("Successfully saved trim with JSON specs")
			}
		} else {
			// 如果没有详细规格，只保存基本信息
            if err := ts.storage.UpsertTrimInfo(&trim); err != nil {
				ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim info")
			}
		}
	}

	ts.logger.WithFields(logrus.Fields{
		"model":       modelName,
		"trims_count": len(trims),
		"layout":      "modern",
	}).Info("Modern layout trim scraping completed")

	return nil
}

// scrapeClassicLayout 抓取经典布局页面 (如Focus)
func (ts *TrimScraper) scrapeClassicLayout(modelName string, pageInfo PageTypeInfo) error {
	ts.logger.WithField("model", modelName).Info("Using classic layout scraping strategy")

    // 经典布局页面需要先点击“See promotion”才能展示所有款式
    // 先获取车型详情页 URL
    detailURL, err := ts.storage.GetVehicleDetailURL(modelName)
    if err != nil {
        ts.logger.WithError(err).WithField("model", modelName).Error("Failed to get detail URL for classic layout")
        return err
    }

    // 使用 Chromedp 抓取实际的款式与价格/链接
    trims, err := ts.scrapeClassicTrimsWithChromedp(modelName, detailURL)
    if err != nil {
        ts.logger.WithError(err).WithField("model", modelName).Warn("Chromedp scraping failed, fallback to basic classic data")
        trims = ts.getMockTrimDataClassic(modelName)
    }

	for _, trim := range trims {
        // 对每个款式，尝试进入 "View promotion" 页面抽取规格
        var specs []models.TrimSpecsInfo
        if trim.ConfigureURL != "" {
            specs = ts.scrapeClassicPromoSpecs(modelName, trim.TrimName, trim.ConfigureURL)
        }
        if len(specs) == 0 {
            // 如果没有真实规格，退回到有限的基础规格
            specs = ts.GetMockSpecsDataClassic(trim.TrimName, modelName)
        }

		// 保存trim信息和有限的规格数据
        if len(specs) > 0 {
            if err := ts.storage.UpsertTrimWithJSONSpecs(&trim, specs); err != nil {
				ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim with JSON specs")

				// 回退到基础保存
                if err := ts.storage.UpsertTrimInfo(&trim); err != nil {
					ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim info")
				}
			}
		} else {
			// 只保存基本信息
            if err := ts.storage.UpsertTrimInfo(&trim); err != nil {
				ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim info")
			}
		}
	}

	ts.logger.WithFields(logrus.Fields{
		"model":       modelName,
		"trims_count": len(trims),
		"layout":      "classic",
		"note":        "Limited specs available due to page structure",
	}).Info("Classic layout trim scraping completed")

	return nil
}

// scrapePerformanceLayout 抓取性能车型页面
func (ts *TrimScraper) scrapePerformanceLayout(modelName string, pageInfo PageTypeInfo) error {
	ts.logger.WithField("model", modelName).Info("Using performance layout scraping strategy")

	// 性能车型可能有独特的规格展示
	trims := ts.getMockTrimDataPerformance(modelName)

	for _, trim := range trims {
		specs := ts.GetMockSpecsDataPerformance(trim.TrimName, modelName)

        if err := ts.storage.UpsertTrimWithJSONSpecs(&trim, specs); err != nil {
			ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim with JSON specs")

            if err := ts.storage.UpsertTrimInfo(&trim); err != nil {
				ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim info")
			}
		}
	}

	ts.logger.WithFields(logrus.Fields{
		"model":       modelName,
		"trims_count": len(trims),
		"layout":      "performance",
	}).Info("Performance layout trim scraping completed")

	return nil
}

// scrapeUnknownLayout 处理未知页面类型
func (ts *TrimScraper) scrapeUnknownLayout(modelName string, pageInfo PageTypeInfo) error {
	ts.logger.WithField("model", modelName).Warn("Unknown page layout, using fallback strategy")

	// 使用最基础的数据结构
	trims := ts.getMockTrimDataFallback(modelName)

	for _, trim := range trims {
        if err := ts.storage.UpsertTrimInfo(&trim); err != nil {
			ts.logger.WithError(err).WithField("trim", trim.TrimName).Error("Failed to save trim info")
		}
	}

	ts.logger.WithFields(logrus.Fields{
		"model":       modelName,
		"trims_count": len(trims),
		"layout":      "unknown_fallback",
		"note":        "Basic trim info only, page structure not recognized",
	}).Info("Unknown layout trim scraping completed with fallback")

	return nil
}

// getMockTrimDataModern 获取现代布局的模拟trim数据 (如Puma)
func (ts *TrimScraper) getMockTrimDataModern(modelName string) []models.TrimInfo {
	var trims []models.TrimInfo

	// 现代布局车型有完整的trim配置对比
	if strings.Contains(strings.ToLower(modelName), "puma gen-e") || strings.Contains(strings.ToLower(modelName), "puma") {
		// Puma Gen-E的trim配置
		trimsData := []struct {
			name        string
			price       float64
			battery     string
			consumption string
			range_miles string
		}{
			{"Select", 29995.00, "43 kWh Standard Range", "13.1 kWh/100km", "233.6 miles"},
			{"Premium", 31995.00, "43 kWh Standard Range", "13.7 kWh/100km", "226.2 miles"},
			{"Sound Edition", 0.00, "43 kWh Standard Range", "13.5 kWh/100km", "230.0 miles"},
		}

		for _, data := range trimsData {
			trim := models.TrimInfo{
				ModelName:             modelName,
				TrimName:              data.name,
				TrimDisplayName:       fmt.Sprintf("Ford %s %s", modelName, data.name),
				Doors:                 &[]int{5}[0],
				Currency:              "GBP",
				BatteryCapacity:       data.battery,
				EnergyConsumption:     data.consumption,
				CO2Emissions:          "0 g/km",
				ChargingTime:          "24 min",
				RangeMiles:            data.range_miles,
				SeeFullSpecsAvailable: true,
				ScrapedAt:             time.Now(),
			}

			if data.price > 0 {
				trim.PriceFrom = &data.price
			}

			trims = append(trims, trim)
		}
	}

	return trims
}

// getMockTrimDataClassic 获取经典布局的模拟trim数据 (如Focus)
func (ts *TrimScraper) getMockTrimDataClassic(modelName string) []models.TrimInfo {
	var trims []models.TrimInfo

	// 🔥 Issue #005: 经典布局页面没有trim对比，只提供基础配置信息
	ts.logger.WithField("model", modelName).Info("Classic layout: limited trim information available")

	// 为经典布局车型提供基础的配置信息
	defaultTrims := []string{"Base", "Titanium"}
	for i, trimName := range defaultTrims {
		trim := models.TrimInfo{
			ModelName:             modelName,
			TrimName:              trimName,
			TrimDisplayName:       fmt.Sprintf("Ford %s %s", modelName, trimName),
			Doors:                 &[]int{5}[0],
			Currency:              "GBP",
			SeeFullSpecsAvailable: false, // 🔥 经典布局没有"See Full Specs"按钮
			ScrapedAt:             time.Now(),
		}

		// 设置基础价格
		basePrice := 20000.00 + float64(i*3000)
		trim.PriceFrom = &basePrice

		trims = append(trims, trim)
	}

	return trims
}

// getMockTrimDataPerformance 获取性能车型的模拟trim数据
func (ts *TrimScraper) getMockTrimDataPerformance(modelName string) []models.TrimInfo {
	var trims []models.TrimInfo

	// 性能车型可能有特殊的配置
	performanceTrims := []string{"ST", "ST-Line"}
	for i, trimName := range performanceTrims {
		trim := models.TrimInfo{
			ModelName:             modelName,
			TrimName:              trimName,
			TrimDisplayName:       fmt.Sprintf("Ford %s %s", modelName, trimName),
			Doors:                 &[]int{5}[0],
			Currency:              "GBP",
			SeeFullSpecsAvailable: true, // 性能车型通常有详细规格
			ScrapedAt:             time.Now(),
		}

		// 性能车型价格通常更高
		basePrice := 35000.00 + float64(i*8000)
		trim.PriceFrom = &basePrice

		trims = append(trims, trim)
	}

	return trims
}

// getMockTrimDataFallback 获取后备的模拟trim数据
func (ts *TrimScraper) getMockTrimDataFallback(modelName string) []models.TrimInfo {
	var trims []models.TrimInfo

	// 🔥 Issue #005: 未知页面类型的降级处理
	ts.logger.WithField("model", modelName).Warn("Unknown page type: providing minimal trim information")

	// 提供最基础的配置信息
	fallbackTrims := []string{"Standard"}
	for _, trimName := range fallbackTrims {
		trim := models.TrimInfo{
			ModelName:             modelName,
			TrimName:              trimName,
			TrimDisplayName:       fmt.Sprintf("Ford %s %s", modelName, trimName),
			Doors:                 &[]int{5}[0],
			Currency:              "GBP",
			SeeFullSpecsAvailable: false, // 未知类型，不提供详细规格
			ScrapedAt:             time.Now(),
		}

		// 基础价格
		basePrice := 25000.00
		trim.PriceFrom = &basePrice

		trims = append(trims, trim)
	}

	return trims
}

// GetMockSpecsDataModern 获取现代布局的完整规格数据 (如Puma)
func (ts *TrimScraper) GetMockSpecsDataModern(trimName, modelName string) []models.TrimSpecsInfo {
	// 这里复用原有的详细规格数据逻辑
	return ts.GetMockSpecsData(trimName, modelName)
}

// GetMockSpecsDataClassic 获取经典布局的有限规格数据 (如Focus)
func (ts *TrimScraper) GetMockSpecsDataClassic(trimName, modelName string) []models.TrimSpecsInfo {
	// 🔥 Issue #005: 经典布局只能提供基础的车型信息，没有详细规格
	ts.logger.WithFields(logrus.Fields{
		"model": modelName,
		"trim":  trimName,
	}).Info("Classic layout: providing basic specs only")

	// 经典布局页面通常只显示这些基础信息
	basicSpecs := []models.TrimSpecsInfo{
		{TrimName: trimName, ModelName: modelName, SpecCategory: "General", SpecName: "Fuel Type", SpecValue: "Petrol", SpecUnit: "", DisplayOrder: 1},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "General", SpecName: "Doors", SpecValue: "5", SpecUnit: "", DisplayOrder: 2},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "General", SpecName: "Transmission", SpecValue: "Manual/Automatic", SpecUnit: "", DisplayOrder: 3},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "SYNC 4", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 4},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Driver Assistance", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 5},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Euro NCAP", SpecValue: "5", SpecUnit: "stars", DisplayOrder: 6},
	}

	for i := range basicSpecs {
		basicSpecs[i].ScrapedAt = time.Now()
	}

	return basicSpecs
}

// GetMockSpecsDataPerformance 获取性能车型的规格数据
func (ts *TrimScraper) GetMockSpecsDataPerformance(trimName, modelName string) []models.TrimSpecsInfo {
	// 性能车型的详细规格
	performanceSpecs := []models.TrimSpecsInfo{
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Engine", SpecValue: "2.3L EcoBoost", SpecUnit: "", DisplayOrder: 1},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Power", SpecValue: "280", SpecUnit: "PS", DisplayOrder: 2},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Torque", SpecValue: "420", SpecUnit: "Nm", DisplayOrder: 3},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "0-100 km/h", SpecValue: "5.8", SpecUnit: "seconds", DisplayOrder: 4},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Top Speed", SpecValue: "250", SpecUnit: "km/h", DisplayOrder: 5},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Drive Type", SpecValue: "Front-wheel drive", SpecUnit: "", DisplayOrder: 6},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Sports Suspension", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 7},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Performance Brakes", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 8},
		{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Sports Seats", SpecValue: "Recaro", SpecUnit: "", DisplayOrder: 9},
	}

	for i := range performanceSpecs {
		performanceSpecs[i].ScrapedAt = time.Now()
	}

	return performanceSpecs
}

// GetMockSpecsData 获取模拟完整规格数据 (Issue #003: 模拟"See Full Specs"完整内容)
func (ts *TrimScraper) GetMockSpecsData(trimName, modelName string) []models.TrimSpecsInfo {
	var specs []models.TrimSpecsInfo

	// 基于trim名称和model名称提供完整规格数据 (模拟点击"See Full Specs"后的内容)
	if strings.Contains(strings.ToLower(modelName), "puma gen-e") || strings.Contains(strings.ToLower(modelName), "puma") {
		// 🔥 Issue #003: Puma Gen-E的完整详细规格 (模拟完整"See Full Specs"内容)
		commonSpecs := []models.TrimSpecsInfo{
			// Performance（性能规格）
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "CO2 Emissions", SpecValue: "0", SpecUnit: "g/km", DisplayOrder: 1},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Top Speed", SpecValue: "105", SpecUnit: "mph", DisplayOrder: 2},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "0-62 mph", SpecValue: "8.8", SpecUnit: "seconds", DisplayOrder: 3},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Range (WLTP Combined)", SpecValue: "233.6", SpecUnit: "miles", DisplayOrder: 4},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Range (WLTP City)", SpecValue: "290", SpecUnit: "miles", DisplayOrder: 5},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Range (WLTP Extra High)", SpecValue: "204", SpecUnit: "miles", DisplayOrder: 6},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Energy Consumption (Combined)", SpecValue: "13.1", SpecUnit: "kWh/100km", DisplayOrder: 7},

			// Battery & Charging（电池和充电规格）
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Battery", SpecName: "Battery Capacity (usable)", SpecValue: "43", SpecUnit: "kWh", DisplayOrder: 1},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Battery", SpecName: "Battery Type", SpecValue: "Lithium-ion", SpecUnit: "", DisplayOrder: 2},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Battery", SpecName: "Battery Warranty", SpecValue: "8 years", SpecUnit: "or 100,000 miles", DisplayOrder: 3},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Charging", SpecName: "DC Fast Charging (10-80%)", SpecValue: "23.2", SpecUnit: "minutes", DisplayOrder: 4},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Charging", SpecName: "AC Charging (0-100%)", SpecValue: "7.4", SpecUnit: "kW", DisplayOrder: 5},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Charging", SpecName: "Charging Port Type", SpecValue: "CCS2", SpecUnit: "", DisplayOrder: 6},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Charging", SpecName: "Regenerative Braking", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 7},

			// Powertrain（动力系统规格）
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Powertrain", SpecName: "Motor Type", SpecValue: "Permanent magnet synchronous", SpecUnit: "", DisplayOrder: 1},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Powertrain", SpecName: "Power Output", SpecValue: "123", SpecUnit: "kW (168 PS)", DisplayOrder: 2},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Powertrain", SpecName: "Torque", SpecValue: "290", SpecUnit: "Nm", DisplayOrder: 3},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Powertrain", SpecName: "Drive Type", SpecValue: "Front-wheel drive", SpecUnit: "", DisplayOrder: 4},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Powertrain", SpecName: "Transmission", SpecValue: "Single-speed automatic", SpecUnit: "", DisplayOrder: 5},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Powertrain", SpecName: "Motor Position", SpecValue: "Front axle", SpecUnit: "", DisplayOrder: 6},

			// Dimensions & Weight（尺寸和重量规格）
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Length", SpecValue: "4186", SpecUnit: "mm", DisplayOrder: 1},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Width (excluding mirrors)", SpecValue: "1805", SpecUnit: "mm", DisplayOrder: 2},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Width (including mirrors)", SpecValue: "2000", SpecUnit: "mm", DisplayOrder: 3},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Height", SpecValue: "1537", SpecUnit: "mm", DisplayOrder: 4},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Wheelbase", SpecValue: "2588", SpecUnit: "mm", DisplayOrder: 5},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Ground Clearance", SpecValue: "150", SpecUnit: "mm", DisplayOrder: 6},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Kerb Weight", SpecValue: "1584", SpecUnit: "kg", DisplayOrder: 7},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Gross Vehicle Weight", SpecValue: "2030", SpecUnit: "kg", DisplayOrder: 8},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Boot Space", SpecValue: "456", SpecUnit: "litres", DisplayOrder: 9},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Boot Space (seats down)", SpecValue: "1216", SpecUnit: "litres", DisplayOrder: 10},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Doors", SpecValue: "5", SpecUnit: "", DisplayOrder: 11},

			// Safety（安全规格）
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Euro NCAP Rating", SpecValue: "5", SpecUnit: "stars", DisplayOrder: 1},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Airbags", SpecValue: "7", SpecUnit: "airbags", DisplayOrder: 2},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Pre-Collision Assist", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 3},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Blind Spot Information System", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 4},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Lane Keeping Aid", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 5},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Traffic Sign Recognition", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 6},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Adaptive Cruise Control", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 7},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Emergency Brake Assist", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 8},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Safety", SpecName: "Cross Traffic Alert", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 9},

			// Technology（技术配置）
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Technology", SpecName: "Driver Display", SpecValue: "12.3", SpecUnit: "inch digital cluster", DisplayOrder: 1},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Technology", SpecName: "Head-Up Display", SpecValue: "Optional", SpecUnit: "", DisplayOrder: 2},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Technology", SpecName: "360° Camera", SpecValue: "Optional", SpecUnit: "", DisplayOrder: 3},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Technology", SpecName: "Park Assist", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 4},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Technology", SpecName: "FordPass Connect", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 5},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Technology", SpecName: "Over-the-Air Updates", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 6},

			// Comfort（舒适配置）
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Comfort", SpecName: "Climate Control", SpecValue: "Dual-zone automatic", SpecUnit: "", DisplayOrder: 1},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Comfort", SpecName: "Seating Capacity", SpecValue: "5", SpecUnit: "seats", DisplayOrder: 2},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Comfort", SpecName: "Driver Seat Adjustment", SpecValue: "8-way power", SpecUnit: "", DisplayOrder: 3},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Comfort", SpecName: "Steering Wheel Adjustment", SpecValue: "4-way manual", SpecUnit: "", DisplayOrder: 4},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Comfort", SpecName: "Electric Windows", SpecValue: "All", SpecUnit: "", DisplayOrder: 5},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Comfort", SpecName: "Remote Central Locking", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 6},
		}

		// 🔥 根据trim添加特定的Features & Equipment规格
		var trimSpecificSpecs []models.TrimSpecsInfo
		switch trimName {
		case "Select":
			trimSpecificSpecs = []models.TrimSpecsInfo{
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Infotainment System", SpecValue: "SYNC 4", SpecUnit: "", DisplayOrder: 1},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Display Size", SpecValue: "12", SpecUnit: "inch touchscreen", DisplayOrder: 2},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Connectivity", SpecValue: "Apple CarPlay & Android Auto", SpecUnit: "", DisplayOrder: 3},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Alloy Wheels", SpecValue: "17", SpecUnit: "inch", DisplayOrder: 4},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Ambient Lighting", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 5},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Heated Front Seats", SpecValue: "No", SpecUnit: "", DisplayOrder: 6},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Wireless Charging", SpecValue: "No", SpecUnit: "", DisplayOrder: 7},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Interior Materials", SpecValue: "Cloth", SpecUnit: "", DisplayOrder: 8},
			}
		case "Premium":
			trimSpecificSpecs = []models.TrimSpecsInfo{
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Infotainment System", SpecValue: "SYNC 4", SpecUnit: "", DisplayOrder: 1},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Display Size", SpecValue: "12", SpecUnit: "inch touchscreen", DisplayOrder: 2},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Connectivity", SpecValue: "Apple CarPlay & Android Auto", SpecUnit: "", DisplayOrder: 3},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Alloy Wheels", SpecValue: "18", SpecUnit: "inch", DisplayOrder: 4},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Ambient Lighting", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 5},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Heated Front Seats", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 6},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Wireless Charging", SpecValue: "Yes", SpecUnit: "", DisplayOrder: 7},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Interior Materials", SpecValue: "Leather", SpecUnit: "", DisplayOrder: 8},
				{TrimName: trimName, ModelName: modelName, SpecCategory: "Features", SpecName: "Premium Audio System", SpecValue: "B&O", SpecUnit: "", DisplayOrder: 9},
			}
		}

		// 合并通用规格和trim特定规格
		commonSpecs = append(commonSpecs, trimSpecificSpecs...)

		// 设置抓取时间
		for i := range commonSpecs {
			commonSpecs[i].ScrapedAt = time.Now()
		}

		specs = commonSpecs
	} else {
		// 其他车型的通用规格 (Issue #003: 为其他车型提供更丰富的规格数据)
		generalSpecs := []models.TrimSpecsInfo{
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Engine", SpecName: "Engine Type", SpecValue: "EcoBoost", SpecUnit: "", DisplayOrder: 1},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Performance", SpecName: "Fuel Type", SpecValue: "Petrol", SpecUnit: "", DisplayOrder: 2},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Dimensions", SpecName: "Doors", SpecValue: "5", SpecUnit: "", DisplayOrder: 3},
			{TrimName: trimName, ModelName: modelName, SpecCategory: "Powertrain", SpecName: "Transmission", SpecValue: "Manual", SpecUnit: "", DisplayOrder: 4},
		}

		for i := range generalSpecs {
			generalSpecs[i].ScrapedAt = time.Now()
		}

		specs = generalSpecs
	}

	return specs
}
